<?php

class Post extends BaseOrm {
	public $Type = 'Post';

	// Columns
	public function Body() {
		$b = trim($this->Values['body']);

		$b = str_replace("\r", '', $b);
		$b = str_replace("<br />", '', $b);
		$b = str_replace("<br/>", '', $b);
		$b = str_replace("<br>", '', $b);
		$b = str_replace("\n\n", '</p><p>', $b);
		$b = str_replace("\n", '<br/>', $b);
		$b = str_replace('&', '&amp;', $b);
		$b = '<p>' . $b . '</p>';

		$b;
		return $b;
	}

	public function CreatePostUrl() {
		return Site::CreatePostReplyUrl($this->Values['id']);
	}

	public function Title() {
		return $this->Values['title'];
	}

	public function Id() {
		return $this->Values['id'];
	}

	public function Created($format = 'F jS, Y') {
		return date($format, $this->Values['created']);
	}

	// STATIC
	public function GetById($id) {
		$query = "
			SELECT
				" . implode(',', self::$EssentialColumns) . "
			FROM
				" . self::$TableName . " AS t
			WHERE
				t." . self::$PrimaryColumn . "=" . intval($id) . "
				AND t.enabled=1
			LIMIT
				1
		";

		return self::_get(self::$Type, $query);
	}

	private $_errors = array();
	public function CreateUpdate($params) {
		$foreign_keys = array(
			'post' => array('class' => 'Post', 'column' => 'post_id'),
			'smiley' => array('class' => 'Smiley', 'column' => 'smiley_id'),
			'usr' => array('class' => 'User', 'column' => 'target_usr_id'),
			'blog' => array('class' => 'Blog', 'column' => 'blog_id'),
		);

		$foreign_key_name = $foreign_keys[$params['target_type']]['column'];
		$foreign_key_value = intval($params['target_id']);
		$foreign_key_class = $foreign_keys[$params['target_type']]['class'];

		if ( !$foreign_key_name || !$foreign_key_value ) {
			self::$_errors['fkey'] = array('error_fkey_not_found');
			return NULL;
		}

		if ( !trim($params['body']) ) {
			self::$_errors['body'] = array('error_body_empty');
			return NULL;
		}

		eval('$target = ' . $foreign_key_class . '::GetById(' . $foreign_key_value . ');');

		if ( !$target ) {
			self::$_errors['target'] = array('error_target_not_valid');
			return NULL;
		}

		$query = "
			INSERT INTO
				msnu_post
			(
				title,
				body,
				created,
				usr_id,
				" . $foreign_key_name . ",
				enabled
			)
			VALUES
			(
				'" . $params['title'] . "',
				'" . $params['body'] . "',
				NOW(),
				" . ((site::$UserId)?site::$UserId:'NULL') . ",
				" . $foreign_key_value . ",
				1
			)
			";

		$result = Dbi::GetResult($query);

		if ( !$result ) {
			self::$_errors['form'] = array('error_insert_failed');
			return false;
		}

		return true;
	}

	public function Errors() {
		if ( !count(self::$_errors) ) return NULL;
		return self::$_errors;
	}
}

class PostList extends BaseOrmList {
	public $Type = 'Post';
}